<template>
    <Teleport to="#after-navigation" v-if="targetExists">
        <ForumManager />
    </Teleport>

    <div>
        <h2>{{ type == 1 ? $t('router_tit.modForum') : $t('router_tit.modForum2') }}</h2>
        <el-button color="#F06423" class="add-forum-btn" @click="showAddForm()"  v-if="roleStore.isSuperAdmin || roleStore.isTeacher">{{ type == 1 ? $t('notice-txt.add-form-btn') : $t('notice-txt.add-form-btn2') }}</el-button>
        <el-form :model="dataForm" ref="ruleFormRef" v-loading="addBtnLoading" :rules="rules" label-width="25%" label-position="left" v-if="(roleStore.isSuperAdmin || roleStore.isTeacher) && isForm">
            <el-form-item :label="$t('notice-txt.add-form.add-form-label1')" required prop="title">
                <el-input v-model="dataForm.title" />
            </el-form-item>
            <el-form-item :label="$t('notice-txt.add-form.add-form-label2')" required prop="content">
                <RichTextEditor v-model="dataForm.content" @update-richValue="dataForm.content = $event" />
            </el-form-item>
            <el-form-item>
                <el-button color="#F06423" v-loading="addBtnLoading" @click="submitForm(ruleFormRef)">{{$t('notice-txt.add-form.add-form-btn-submit')}}</el-button>
                <el-button color="#435764" @click="hideAddForm()">{{$t('notice-txt.add-form.add-form-btn-cancel')}}</el-button>
                <!-- <el-button color="#F06423" link>進階</el-button> -->
            </el-form-item>
        </el-form>
        <el-table :data="dataList" v-loading="loading">
            <el-table-column :label="$t('notice-txt.table-txt.table-label1')">
                <template #default="{ row }">
                    <RouterLink :to="{ name: `modForumDiscuss`, query: { id: row.id} }">
                        <img src="@/assets/img/title-icon.png" style="display: inline-block; margin-right: 15px;" />
                        <span>{{ row.title }}</span>
                    </RouterLink>
                </template>
            </el-table-column>
            <el-table-column :label="$t('notice-txt.table-txt.table-label2')" width="190">
                <template #default="{ row }">
                    <div class="user-box">
                        <div class="user-picture pic">
                            <img :src="row.creator.avatar_url" v-if="row.creator && row.creator.avatar_url" />
                            <el-icon size="20" color="#fff" v-else><User /></el-icon>
                        </div>
                        <div class="user-info">
                            <div class="fullname">{{ row.creator.name }}</div>
                            <div class="date">{{ moment.unix(row.created_at).format('DD MMM YYYY') }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column :label="$t('notice-txt.table-txt.table-label3')" width="190">
                <template #default="{ row }">
                    <div class="user-box">
                        <div class="user-picture pic">
                            <img :src="row.newComment.avatar_url" v-if="row.newComment && row.newComment.avatar_url" />
                            <el-icon size="20" color="#fff" v-else><User /></el-icon>
                        </div>
                        <div class="user-info">
                            <div class="fullname">{{ row.newComment && row.newComment.name }}</div>
                            <div class="date">{{ row.newComment && moment.unix(row.newComment.created_at).format('DD MMM YYYY') }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="respond" :label="$t('notice-txt.table-txt.table-label4')" width="50">
                <template #default="{ row }">
                    <span>{{row.commentNum || 0}}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column width="50">
                <template #default="{ row }">
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            <el-icon size="16"><MoreFilled /></el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item>將討論標記星號</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column> -->
        </el-table>
        <div class="pagination-box">
            <el-pagination
                background
                v-model:page-size="pagination.limit"
                v-model:current-page="pagination.page"
                layout="sizes, prev, pager, next"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                class="mt-4"
                :hide-on-single-page="true"
                @size-change="getDataList"
                @current-change="getDataList"
            />
        </div>
        <!-- <el-empty description="(目前還沒有發佈消息)" image=" " v-else /> -->
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import moment from 'moment'
moment.locale('en');
import RichTextEditor from '@/components/RichTextEditor.vue'
import ForumManager from '@/components/ForumManager.vue'
import CourseService from '@/api/course'
const route = useRoute()
import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
// 課程id
const courseId = computed(() => Number(route.query.courseId))
// 類型
const type = computed(() => Number(route.query.type))
const targetExists = ref(false)
import { useRoleStore } from '@/stores/role'
const roleStore = useRoleStore()
import type { FormInstance, FormRules } from 'element-plus'

// 讨论区表格
const dataList = ref([])
const loading = ref(false);
import type { Pagination } from '@/types/global'
// 分页器
const pagination = ref<Pagination>({
    page: 1,
    limit: 10,
    total: 10,
})
const getDataList = () => {
    loading.value = true;
    const params = {
        courseId: courseId.value,
        type: type.value,
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    CourseService.getCourseNotice(params).then(res => {
        dataList.value = res.dataList || [];
        pagination.value = res.pagination || pagination.value
    }).finally(() => {
        loading.value = false;
    })
}
// 新增
const isForm = ref(false)
const showAddForm = () => {
    isForm.value = true;
}
const hideAddForm = () => {
    dataForm.title = '';
    dataForm.content = '';
    isForm.value = false;
}
const ruleFormRef = ref<FormInstance>()
const dataForm = reactive({
    title: '',
    content: '',
})
const rules = reactive({
  title: [
    {
      required: true,
      message: t("notice-txt.add-form.add-form-rules1"),
      trigger: 'blur',
    },
  ],
  content: [
    {
      required: true,
      message: t("notice-txt.add-form.add-form-rules2"),
      trigger: 'blur',
    },
  ],
})
// 新增课程公告

const submitForm = async (formEl: { validate: (arg0: (valid: any, fields: any) => void) => any }) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addCourseNoticeAction()
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 提交
const addBtnLoading = ref(false);
const addCourseNoticeAction = () => {
    addBtnLoading.value = true;
    const params = {
        course_id: courseId.value,
        title: dataForm.title,
        content: dataForm.content,
        type: type.value,
        status: 1,
        sort_order: 0,
    };
    CourseService.postCourseNotice(params).then(res => {
        pagination.value.page = 1;
        hideAddForm();
        getDataList();
        
    }).finally(() => {
        addBtnLoading.value = false;
    })
}
// 监听路由参数变化
watch(
  () => route.query, 
  (newParams, oldParams) => {
    getDataList();
    // 执行参数变化后的逻辑（如重新加载数据）
  },
  { immediate: true } // 初始加载时立即执行一次
)

onMounted(() => {
    targetExists.value = !!document.querySelector('#after-navigation')
})
</script>

<style lang="less" scoped>
.date{
    font-size: 12px;
}
.pagination-box{
    justify-content: center;
    margin-top: 25px;
}
.user-picture{
    border-radius: 50%;
}
.user-info{
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
}
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.add-forum-btn {
    margin-bottom: 30px;
    color: #fff;
}

.el-form {
    .el-button {
        &.is-link {
            color: #4c4c4c;

            &:hover {
                color: #f06423;
            }
        }
    }
}

:deep(.ck-editor) {
    width: 100%;

    .ck-editor__main {
        .ck-content {
            min-height: 350px;
            max-height: 600px;
        }
    }
}

.el-empty {
    --el-empty-padding: 10px 0;
    --el-empty-description-margin-top: 0;

    .el-empty__image {
        display: none;
    }
}
</style>
